/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.lanchat.model.net;

import com.lanchat.model.data.User;
import com.lanchat.model.util.ChatByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.LinkedList;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * 用于发送信息的类
 * 
 * @author Zhangyiheng
 */
public class UdpSend {

    private DatagramSocket ds;
    private ChatByteArrayOutputStream buffer;

    public UdpSend() {
        try {
            ds = new DatagramSocket();
            buffer = new ChatByteArrayOutputStream(NetConstant.DATAGRAMPACKET_SIZE);
        } catch (SocketException ex) {
            Logger.getLogger(UdpSend.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    public synchronized  void send(Object data,String ip){
        ObjectOutputStream outStream= null;
        try {
            buffer.reset();
            outStream = new ObjectOutputStream(buffer);
            outStream.writeObject(data);
            outStream.flush();
            InetAddress address=InetAddress.getByName(ip);
            DatagramPacket dp=new DatagramPacket(buffer.getBuf(),buffer.size(),
                                    address,NetConstant.UDPCHATPORT);
            ds.send(dp);
        } catch (IOException ex) {
            Logger.getLogger(UdpSend.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                outStream.close();
            } catch (IOException ex) {
                Logger.getLogger(UdpSend.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    public void BroadcastSend(Object data,LinkedList<String> list){
        ObjectOutputStream out=null;
        for(int i=0;i<list.size();i++){
            buffer.reset();
            try {
                InetAddress addr = InetAddress.getByName(list.get(i));
                out = new ObjectOutputStream(buffer);
                out.writeObject(data);
                out.flush();
                DatagramPacket dp=new DatagramPacket(buffer.getBuf(), buffer.size(),
                        addr,NetConstant.UDPCHATPORT);
                ds.send(dp);
            } catch (IOException ex) {
                Logger.getLogger(UdpSend.class.getName()).log(Level.SEVERE, null, ex);
            } finally{
                try {
                    out.close();
                } catch (IOException ex) {
                    Logger.getLogger(UdpSend.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }
    public void dispose(){
        buffer=null;
        ds.close();
        ds=null;
    }
}
